import React, { useEffect, useRef, useState } from 'react';
import ProForm, { 
  ModalForm, 
  ProFormText, 
  ProFormSelect, 
  ProFormDigit, 
  ProFormCheckbox, 
  ProFormDateTimePicker
} from '@ant-design/pro-form';
import { Form, FormInstance, Tooltip } from 'antd';
import { useModel } from 'umi';
import { 
  getCategoryListByPage,
  getGoodsListByPage, 
  getGoodsSpecsList
} from '@/services/stock-goods/api';
import { getFrequencyCodesList1 } from '@/services/params/api';
import { createPlanOrder, predictFee } from '@/services/order/api';
import { showMsg, formatDate, getDateValue, MsgType, inArray, isNull } from '@/utils/utils';
import { OptType } from '@/utils/constants';
import { history } from 'umi';
import moment from 'moment';

interface OptFormProps {
  handleAdd: (values: any) => Promise<boolean>;
  handleModalVisible: (visible: boolean) => void;
  patientHospitalInfo?: ORDERAPI.PatientHospitalInfo;
  record?: any;
  actionRef?: any;
  order_id?: string;
  optType: string;
}

const rules = [
  {
    required: true
  }
]

const OptForm: React.FC<OptFormProps> = (props) => {
  const { 
    handleModalVisible, 
    record = {},  
    handleAdd, 
    patientHospitalInfo,
    actionRef,
    order_id,
    optType
  } = props;

  const { initialState } = useModel('@@initialState');
  const [classList, setClassList]= useState<STOCKGOODSAPI.CategoryItem[]>([]);
  const [goodsList, setGoodsList] = useState<STOCKGOODSAPI.GoodsItem[]>([]);
  const [goodsSpecsList, setGoodsSpecsList] = useState<STOCKGOODSAPI.GoodsSpecsItem[]>([]);
  const [frequencyCodesList, setFrequencyCodesList] = useState<PARAMSAPI.FrequencyCodesItem[]>([]);
  const formRef = useRef<FormInstance>();
  const [endTimeReq, setEndTimeReq] = useState<boolean>(true);
  const [loading, setLoading] = useState<boolean>(false);
  const [curGood, setCurGood] = useState({});

  // 分类列表
  const fetchClassList = async () => {
    const data: STOCKGOODSAPI.CategoryItemList = await getCategoryListByPage({
      current: 1,
      pageSize: 10000
    });
    const list: STOCKGOODSAPI.CategoryItem[] = [];
    data.record_list?.forEach(item => {
      if (item.create_dept_code === initialState?.currentUser?.dept_code) {
        list.push(item);
      }
    });
    setClassList(list || []);
  }

   // 商品列表
  const fetchGoodsList = async (class_id?:string) => {
    const params = {
      current: 1,
      pageSize: 10000
    }
    if (class_id) {
      params['class_id'] = class_id;
    } 
    const data: STOCKGOODSAPI.GoodsItemList = await getGoodsListByPage(params);
    const list: STOCKGOODSAPI.GoodsItem[] = [];
    data.record_list?.forEach((item) => {
      // 筛选本科室的商品
      if (item.create_dept_code === initialState?.currentUser?.dept_code) {
        list.push(item);
      }
    });
    setGoodsList(list);
  }

  // 商品规格
  const fetchGoodsSpecsList = async (goods_id: string, goods_dept_code: string) => {
    const data: STOCKGOODSAPI.GoodsSpecsItemList = await getGoodsSpecsList({
      goods_id,
      goods_dept_code,
      current: 1,
      pageSize: 10000
    });
    setGoodsSpecsList(data.record_list || []);
    if (data.record_list?.length === 1) {
      formRef.current?.setFieldsValue({
        specs_id: data.record_list[0]?.specs_id,
        goods_price: Number(data.record_list[0]?.selling_price).toFixed(2)
      });
      calcPredictFee();
    }
  }

  // 执行频次
  const fetchFreqencyCodeList = async () => {
    try {
      const data: PARAMSAPI.FrequencyCodesList = await getFrequencyCodesList1({current: 1, pageSize: 1000});
      setFrequencyCodesList(data.record_list || []);
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  // 计算费用预估
  const calcPredictFee = async () => {
    const values = formRef.current?.getFieldsValue();
    const { begin_time, end_time, frequency_id, is_first, goods_price, use_num } = values;
    // 结束时间有值，则去掉勾选长期计划
    if (end_time) {
      setEndTimeReq(true);
      formRef.current?.setFieldsValue({ is_long: false });
    }
    if (begin_time && end_time && frequency_id && goods_price && use_num) {
      console.log(begin_time, end_time)
      const result: any = await predictFee({
        begin_time: typeof begin_time === 'string' ? formatDate(begin_time): begin_time.format('YYYYMMDDHHmmss'),
        end_time: typeof end_time === 'string' ? formatDate(end_time) : end_time.format('YYYYMMDDHHmmss'),
        frequency_id: frequency_id,
        is_first: is_first ? '1' : '0',
        goods_price: goods_price,
        use_num: use_num
      });

      formRef.current?.setFieldsValue({
        predict_price: result.predict_price,
      });
    } else {
      formRef.current?.setFieldsValue({
        predict_price: null
      });
    }
  }

  useEffect(() => {
    fetchClassList();
    fetchGoodsList();
    fetchFreqencyCodeList();
  }, []);

  useEffect(() => {
    if (optType === OptType.EDIT || optType === OptType.COPY) {
      fetchGoodsSpecsList(record.goods_id, record.create_dept_code);
      setEndTimeReq(record.is_long !== '1');
    }
    calcPredictFee();
    console.log('record', record);
  }, [optType, record]);
  
  const renderClass = () => {
    const list1 = [];
    classList.map(item => {
      list1.push({
        label: `${item.class_name}（${item.class_py}）`,
        value: item.class_id as string,
        class_name: item.class_name,
      })
    })
    if (!isNull(curGood.class_id) && !inArray(classList, curGood.class_id, 'bol', 'class_id')) {
      list1.push({
        label: `${curGood.class_name}`,
        value: curGood.class_id,
        disabled: true,
      })
    }
    return list1;
  }

  return <ModalForm
      title="新建/编辑项目计划"
      width="90%"
      visible
      modalProps={{
        maskClosable: false
      }}
      layout="horizontal"
      className="add-plan-dialog"
      formRef={formRef}
      onVisibleChange={handleModalVisible}
      onFinish={async (values) => {
        console.log(values);
        if (!values['is_long']) {
          if (values.begin_time && values.end_time) {
            if (getDateValue(values.begin_time) > getDateValue(values.end_time)) {
              showMsg('结束时间不能早于开始时间', MsgType.INFO);
              return;
            }
          }
        }
        if (loading) {
          return;
        }
        setLoading(true);
        try {
          let createPlanOrderRes: any = null;
          // 没有计划订单编号，先创建计划订单
          if (!order_id) {
            const params = {
              address: patientHospitalInfo?.address,
              admission_num: patientHospitalInfo?.visit_no,
              bed_no: patientHospitalInfo?.bed_no,
              identity_no: patientHospitalInfo?.identity_no,
              mobile: patientHospitalInfo?.contact_tel_no,
              order_person: initialState?.currentUser?.oper_name,
              order_person_id: initialState?.currentUser?.oper_id,
              patient_dept_code: patientHospitalInfo?.admission_dept_code,
              patient_dept_name: patientHospitalInfo?.admission_dept_name,
              patient_id: patientHospitalInfo?.patient_id,
              patient_name: patientHospitalInfo?.patient_name,
              ward: patientHospitalInfo?.ward_code,
              ic_card_no: patientHospitalInfo?.ic_card_no
            }
            createPlanOrderRes = await createPlanOrder(params)
          }
  
          const { class_id, goods_id, frequency_id, specs_id } = values;
          const goods = goodsList.find(item => item.goods_id === goods_id);
          const specs = goodsSpecsList.find(item => item.specs_id === specs_id);
  
          const data = {
            order_id: createPlanOrderRes?.order_id || order_id,
            class_name: classList.find(item => item.class_id === class_id)?.class_name,
            frequency_name: frequencyCodesList.find(item => item.frequency_id === frequency_id)?.frequency_name,
            goods_name: goods?.goods_name,
            goods_dept_code: goods?.create_dept_code,
            brand_id: goods?.brand_id,
            brand_name: goods?.brand_name,
            ...specs,
            ...values,
            begin_time: formatDate(values.begin_time),
            end_time: values.end_time ? formatDate(values.end_time) : '',
            is_first: values['is_first'] ? 1 : 0,
            is_long: values['is_long'] ? 1: 0
          }
          // 编辑
          if (optType === OptType.EDIT) {
            data['project_id'] = record.project_id;
          }
          const success = await handleAdd(data as any);
          setLoading(false);
          if (success) {
            handleModalVisible(false);
            if (!order_id) {
              history.replace({
                pathname: '/order/planOrder/detail',
                query: {
                  order_id: createPlanOrderRes.order_id
                }
              })
            } else {
              actionRef.current?.reload();
            }
          }
        } catch (error) {
          console.log(error)
          setLoading(false);
          showMsg(error?.data?.errmsg);
        }
      }}
      submitter={{
        searchConfig: {
          resetText: '取消',
          submitText: '保存'
        },
        submitButtonProps: {
          loading: loading
        }
      }}>
      <ProForm.Group>
        <Form.Item label="患者姓名">
          <span className="fwb c333">{patientHospitalInfo?.patient_name}</span>
        </Form.Item>
        <Form.Item label="住院号">
          <span className="fwb c333">{patientHospitalInfo?.admission_num}</span>
        </Form.Item>
        <Form.Item label="归属科室">
          <span className="fwb c333">{patientHospitalInfo?.admission_dept_name || patientHospitalInfo?.admission_dept_code}</span>
        </Form.Item>
        <Form.Item label="床位号">
          <span className="fwb c333">{patientHospitalInfo?.bed_no}</span>
        </Form.Item>
      </ProForm.Group>
     
      <ProForm.Group>
        <ProFormSelect
          name="class_id"
          label="商品分类"
          width="sm"
          initialValue={record.class_id}
          options={renderClass()}
          fieldProps={{
            onChange: (value: string) => {
              fetchGoodsList(value);
              formRef.current?.setFieldsValue({
                goods_id: null,
                specs_id: null,
                goods_price: null
              })
            }
          }}
        />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormSelect
          rules={rules}
          label="商品名称"
          width="sm"
          name="goods_id"
          showSearch
          initialValue={record.goods_id}
          options={goodsList.filter(item => {
            return item.can_inventory > 0
          }).map(item => {
            return {
              label: `【${item.brand_name}】${item.goods_name}（${item.goods_py}）` ,
              value: item.goods_id as string,
              data: item,
            }
          })}
          fieldProps={{
            showSearch: true,
            onChange: (value: string) => {
              console.log('value', value)
              
              const goods = goodsList.find(item => item.goods_id === value);
              fetchGoodsSpecsList(value, goods?.create_dept_code);
              console.log(goods);
              formRef.current?.setFieldsValue({
                goods_id: goods?.goods_id,
                class_id: goods?.class_id,
                specs_id: null,
                goods_price: null
              })
            },
            onSelect: (val, opt) => {
              setCurGood(opt.data);
            }
          }}
        />
        <ProFormSelect
          rules={rules}
          label="商品规格"
          width="sm"
          name="specs_id"
          initialValue={record.specs_id}
          options={goodsSpecsList.map(item => {
            return {
              disabled: Number(item.inventory) <= 0,
              label: <Tooltip title={`剩余${item.can_inventory}`}><div>{item.specs_name}</div></Tooltip>,
              value: item.specs_id as string
            }
          })}
          fieldProps={{
            onChange: (value) => {
              console.log(value)
              const goodsSpec = goodsSpecsList.find(item => item.specs_id === value);
              console.log(goodsSpec)
              formRef.current?.setFieldsValue({
                goods_price: Number(goodsSpec?.selling_price).toFixed(2)
              });

              calcPredictFee();
            }
          }}
        />

        <ProFormText label="单价" 
          rules={rules}
          name="goods_price"
          width="sm"
          initialValue={record.goods_price && Number(record.goods_price).toFixed(2)}
          readonly
        />
        <Form.Item style={{marginLeft: -25}}>元</Form.Item>
      </ProForm.Group>
     
      <ProForm.Group>
        <ProFormSelect
          rules={rules}
          label="执行频次"
          name="frequency_id"
          width="sm"
          initialValue={record.frequency_id}
          options={frequencyCodesList.map(item => {
            return {
              label: item.frequency_id,
              value: item.frequency_id
            }
          })}
          fieldProps={{
            showSearch: true,
            filterOption: false,
            onChange: (value: string) => {
              console.log(value);
              calcPredictFee();
              formRef.current?.setFieldsValue({
                frequency_desc: frequencyCodesList.find(item => item.frequency_id === value)?.frequency_desc
              })
            }
          }}
        />
        <ProFormText
          label="执行描述"
          name="frequency_desc"
          width="sm"
          initialValue={record.frequency_desc}
        />
      </ProForm.Group>
      
      <ProForm.Group>
        <ProFormDateTimePicker
          rules={rules}
          label="开始时间"
          width="sm"
          name="begin_time"
          fieldProps={{
            showTime: { defaultValue: moment('00:00:00', 'HH:mm:ss')},
            onChange: () => {
              calcPredictFee()
            }
          }}
          initialValue={record.begin_time}
        />
        <ProFormDateTimePicker
          rules={[
            {
              required: endTimeReq
            }
          ]}
          label="结束时间"
          width="sm"
          name="end_time"
          fieldProps={{
            showTime: { defaultValue: moment('23:59:59', 'HH:mm:ss')},
            onChange: () => {
              calcPredictFee()
            }
          }}
          initialValue={record.end_time}
        />
        <ProFormCheckbox
          width="sm"
          className="mb0"
          name="is_long"
          fieldProps={{
            onChange: (e) => {
              const checked = e.target.checked;
              setEndTimeReq(!checked);
              // 勾选了长期计划，则清空结束时间和预估费用
              if (checked) {
                formRef.current?.setFieldsValue({
                  end_time: null,
                  predict_price: null
                })
              }
            }
          }}
          initialValue={Number(record.is_long) === 1}>长期计划</ProFormCheckbox>
      </ProForm.Group>
      
      <ProForm.Group>
        <ProFormDigit
          label="单次用量"
          width="sm"
          rules={rules}
          name="use_num"
          initialValue={record.use_num}
          fieldProps={{
            onBlur: () => {
              calcPredictFee()
            }
          }}
        />
        <ProFormCheckbox 
          className="checkbox"
          width="md"
          style={{
            marginBottom: 0,
            marginLeft: 30
          }}
          initialValue={Number(record.is_first) === 1}
          fieldProps={{
            onChange: (e: any) => {
              calcPredictFee();
            }
          }}
          name="is_first">
          增加首次消耗用量（单次用量 * 1）
        </ProFormCheckbox>
      </ProForm.Group>

      <ProForm.Group>
        <ProFormDigit
          label="费用预估"
          width="sm"
          name="predict_price"
          initialValue={record.predict_price}
          fieldProps={{
            precision: 2
          }}
        />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormText
          label="责任人"
          width="sm"
          name="oper_name"
          initialValue={initialState?.currentUser?.oper_name}
        />
        <ProFormText
          label="备注"
          width="sm"
          name="remarks"
          initialValue={record.remarks}
        />
        <Form.Item label="计划创建人">
         <div style={{fontSize: 12}}>{initialState?.currentUser?.oper_name}</div>
        </Form.Item>
      </ProForm.Group>
    </ModalForm>
}
export default OptForm;
